<?php
namespace App\Repos;

use App\Models\UserMoneyLog;
use App\Models\UserShopMoney;
use App\Models\User;
use App\Services\WechatTpl;
use DB;

class UserMoneyLogRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$fields = ['id','shop_id','user_id','order_id','money','craeted_at'];
	  	$list = UserMoneyLog::select($fields)
	  							->with('user:id,nickname,phone')
	  							->with('order:id,code')
	  							->with('shop:id,name')
	  							->where($where)->paginate($num); 	  	
	  	return $list;     
	}

	/**
	 ** 添加余额记录	  
	 */
	public static function create($data)
	{		
		$rs['status'] = false;
		try {
			DB::beginTransaction();
			$user = User::find($data['user_id']);

			// 用户店铺余额
			$usm['user_id'] = $data['user_id'];
			$usm['shop_id'] = $data['shop_id'];
			$shopMoney = UserShopMoney::where($usm)->first();
			if(array_get($data,'type')==2) {
				// 如果消费就要减掉
				$user->money = $user->money-$data['money'];
				if($shopMoney) {
					$shopMoney->money   = $shopMoney->money-$data['money'];
					$shopMoney->save();		
				}
				
			} else {
				// 拍十秒不累加
				if(array_get($data,'type')!=3) {
					$user->money = $user->money+$data['money'];	
				}
				

				//用户店铺余额增加				
				if($shopMoney){
					$shopMoney = $shopMoney+$data['money'];
					$shopMoney->save();	
				} else {
					$usmData = array_only($data,['user_id','shop_id','money']);
					UserShopMoney::create($usmData);
				}
			}
			$user->save();
			// 记录日志
			UserMoneyLog::create($data);
			
			
			

			DB::commit();
			$rs['status'] = true;
			return $rs; 						
			
		} catch (\Exception $e) {
			DB::rollback();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		return $rs;		
	}

	
	
	
	

	
	
	
}